package com.linwen.tips.reflex;

import lombok.SneakyThrows;
import org.junit.Test;

import java.lang.reflect.Constructor;

/**
 * @ClassName ReflectTest
 * @Description TODO
 * @Author zero
 * @DATE 2024/9/9 11:59 PM
 * @Version 1.0
 */
public class ReflectTest {
    @Test
    public void test() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000_0000; i++) {
            UserInfoPO userInfo = new UserInfoPO();
        }
        System.out.println("普通创建对象耗时："+(System.currentTimeMillis() - start));
    }

    @SneakyThrows
    @Test
    public void test1() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000_0000; i++) {
            // 默认无参构造函数
            UserInfoPO userInfo = UserInfoPO.class.newInstance();
        }
        System.out.println("反射创建对象耗时："+(System.currentTimeMillis() - start));
    }

    @SneakyThrows
    @Test
    public void test2() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000_0000; i++) {
            Constructor<UserInfoPO> constructor = UserInfoPO.class.getConstructor();
            UserInfoPO userInfo = constructor.newInstance();
        }
        System.out.println("反射2创建对象耗时："+(System.currentTimeMillis() - start));
    }

    @SneakyThrows
    @Test
    public void test3() {
        long start = System.currentTimeMillis();
        // 提前获取构造函数
        Constructor<UserInfoPO> constructor = UserInfoPO.class.getConstructor();
        for (int i = 0; i < 1000_0000; i++) {
            UserInfoPO userInfo = constructor.newInstance();
        }
        System.out.println("反射3创建对象耗时："+(System.currentTimeMillis() - start));
    }

    @SneakyThrows
    @Test
    public void test4() {
        long start = System.currentTimeMillis();
        Constructor<UserInfoPO> constructor = UserInfoPO.class.getConstructor();
        // 禁用反射安全检测
        constructor.setAccessible(true);
        for (int i = 0; i < 1000_0000; i++) {
            UserInfoPO userInfo = constructor.newInstance();
        }
        System.out.println("反射4创建对象耗时："+(System.currentTimeMillis() - start));
    }
}
